import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/index.dart';
import 'package:flutter_hplus/components/tables/index.dart';
import 'package:flutter_hplus/theme/theme.dart';

/// 按钮表格页面
/// 
/// 展示在表格中使用按钮和其他交互控件的示例
class ButtonTablePage extends StatefulWidget {
  /// 构造函数
  const ButtonTablePage({super.key});

  @override
  State<ButtonTablePage> createState() => _ButtonTablePageState();
}

class _ButtonTablePageState extends State<ButtonTablePage> {
  // 用户数据
  final List<Map<String, dynamic>> _userData = [
    {'username': 'admin', 'nickname': '管理员', 'lastLogin': '2023-10-15 14:30', 'status': true, 'id': '001'},
    {'username': 'user1', 'nickname': '用户1', 'lastLogin': '2023-10-14 09:45', 'status': true, 'id': '002'},
    {'username': 'user2', 'nickname': '用户2', 'lastLogin': '2023-10-13 16:20', 'status': false, 'id': '003'},
    {'username': 'editor', 'nickname': '编辑人员', 'lastLogin': '2023-10-12 11:35', 'status': true, 'id': '004'},
    {'username': 'guest', 'nickname': '访客', 'lastLogin': '2023-10-10 08:15', 'status': false, 'id': '005'},
    {'username': 'tester', 'nickname': '测试人员', 'lastLogin': '2023-10-09 13:50', 'status': true, 'id': '006'},
    {'username': 'dev1', 'nickname': '开发者1', 'lastLogin': '2023-10-08 10:25', 'status': true, 'id': '007'},
    {'username': 'dev2', 'nickname': '开发者2', 'lastLogin': '2023-10-07 15:40', 'status': false, 'id': '008'},
    {'username': 'manager', 'nickname': '经理', 'lastLogin': '2023-10-06 09:10', 'status': true, 'id': '009'},
    {'username': 'analyst', 'nickname': '分析师', 'lastLogin': '2023-10-05 14:05', 'status': true, 'id': '010'},
  ];
  
  // 表格列定义
  late List<HDataColumn> _columns;
  
  @override
  void initState() {
    super.initState();
    _initColumns();
  }
  
  // 初始化列定义
  void _initColumns() {
    _columns = [
      const HDataColumn(
        label: '用户名',
        field: 'username',
      ),
      const HDataColumn(
        label: '昵称',
        field: 'nickname',
      ),
      const HDataColumn(
        label: '上次登录',
        field: 'lastLogin',
      ),
      HDataColumn(
        label: '状态',
        field: 'status',
        cellBuilder: (value, rowData, rowIndex) {
          bool isActive = value as bool;
          return SwitcMyButton(
            value: isActive,
            activeText: '正常',
            inactiveText: '锁定',
            onChanged: (newValue) {
              setState(() {
                _userData[rowIndex]['status'] = newValue;
              });
            },
          );
        },
      ),
      HDataColumn(
        label: '操作',
        field: 'id',
        cellBuilder: (value, rowData, rowIndex) {
          return Row(
            children: [
              // 编辑按钮
              SizedBox(
                width: 46,
                child: MyButton(
                  text: '编辑',
                  type: MyButtonType.info,
                  size: MyButtonSize.small,
                  onPressed: () => _editUser(rowData, rowIndex),
                ),
              ),
              const SizedBox(width: 8),
              // 删除按钮
              SizedBox(
                width: 46,
                child: MyButton(
                  text: '删除',
                  type: MyButtonType.danger,
                  size: MyButtonSize.small,
                  onPressed: () => _deleteUser(rowData, rowIndex),
                ),
              ),
            ],
          );
        },
      ),
    ];
  }
  
  // 编辑用户
  void _editUser(Map<String, dynamic> userData, int index) {
    // 创建一个副本用于编辑
    Map<String, dynamic> editingData = Map<String, dynamic>.from(userData);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('编辑用户'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                decoration: const InputDecoration(labelText: '用户名'),
                controller: TextEditingController(text: editingData['username']),
                onChanged: (value) => editingData['username'] = value,
              ),
              TextField(
                decoration: const InputDecoration(labelText: '昵称'),
                controller: TextEditingController(text: editingData['nickname']),
                onChanged: (value) => editingData['nickname'] = value,
              ),
              SwitchListTile(
                title: const Text('状态'),
                value: editingData['status'] as bool,
                onChanged: (value) => setState(() => editingData['status'] = value),
              ),
            ],
          ),
        ),
        actions: [
          MyButton(
            text: '取消',
            type: MyButtonType.defaultType,
            size: MyButtonSize.small,
            onPressed: () => Navigator.of(context).pop(),
          ),
          MyButton(
            text: '保存',
            type: MyButtonType.primary,
            size: MyButtonSize.small,
            onPressed: () {
              setState(() {
                _userData[index] = editingData;
              });
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }
  
  // 删除用户
  void _deleteUser(Map<String, dynamic> userData, int index) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除用户 ${userData['nickname']} (${userData['username']}) 吗？'),
        actions: [
          MyButton(
            text: '取消',
            type: MyButtonType.defaultType,
            size: MyButtonSize.small,
            onPressed: () => Navigator.of(context).pop(),
          ),
          MyButton(
            text: '删除',
            type: MyButtonType.danger,
            size: MyButtonSize.small,
            onPressed: () {
              setState(() {
                _userData.removeAt(index);
              });
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }
  
  // 添加新用户
  void _addUser() {
    Map<String, dynamic> newUser = {
      'username': '',
      'nickname': '',
      'lastLogin': DateTime.now().toString().substring(0, 16),
      'status': true,
      'id': DateTime.now().millisecondsSinceEpoch.toString(),
    };
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('添加用户'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                decoration: const InputDecoration(labelText: '用户名'),
                onChanged: (value) => newUser['username'] = value,
              ),
              TextField(
                decoration: const InputDecoration(labelText: '昵称'),
                onChanged: (value) => newUser['nickname'] = value,
              ),
              SwitchListTile(
                title: const Text('状态'),
                value: newUser['status'] as bool,
                onChanged: (value) => setState(() => newUser['status'] = value),
              ),
            ],
          ),
        ),
        actions: [
          MyButton(
            text: '取消',
            type: MyButtonType.defaultType,
            size: MyButtonSize.small,
            onPressed: () => Navigator.of(context).pop(),
          ),
          MyButton(
            text: '添加',
            type: MyButtonType.primary,
            size: MyButtonSize.small,
            onPressed: () {
              if (newUser['username'].toString().trim().isNotEmpty &&
                  newUser['nickname'].toString().trim().isNotEmpty) {
                setState(() {
                  _userData.add(newUser);
                });
                Navigator.of(context).pop();
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('用户名和昵称不能为空')),
                );
              }
            },
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    return Container(
      padding: EdgeInsets.only(top: theme.dimens.spacingM),
      color: theme.colors.background,
      // 使用Column和Expanded来铺满剩余空间
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: _buildTableCard(
              theme: theme,
              title: '用户管理表格',
              subtitle: '状态切换、操作按钮',
              content: HDataTable(
                columns: _columns,
                data: _userData,
                showBorder: true,
                showStripes: true,
                showHover: true,
                enablePagination: true,
                enableSearch: true,
                leftActions: [
                  // 添加用户按钮，放置在表格头部左侧
                  MyButton(
                    text: '添加用户',
                    type: MyButtonType.primary,
                    size: MyButtonSize.small,
                    onPressed: _addUser,
                  ),
                ],
                // onRowTap: (row) {
                //   ScaffoldMessenger.of(context).showSnackBar(
                //     SnackBar(content: Text('选中用户: ${row['nickname']} (${row['username']})')),
                //   );
                // },
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  /// 构建表格卡片
  Widget _buildTableCard({
    required HTheme theme,
    required String title,
    required Widget content,
    String? subtitle,
    List<Widget>? headerActions,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(0), // 方形卡片
      ),
      margin: EdgeInsets.zero,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 卡片标题
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            child: Row(
              children: [
                Text(
                  title,
                  style: theme.textStyles.h3,
                ),
                if (subtitle != null) ...[
                  const SizedBox(width: 8),
                  Text(
                    subtitle,
                    style: theme.textStyles.secondary.copyWith(
                      fontSize: 12,
                    ),
                  ),
                ],
                
                const SizedBox(width: 16),
                // 头部操作按钮
                if (headerActions != null) ...headerActions,
              ],
            ),
          ),
          
          // 卡片内容 - 使用Expanded包裹内容区域
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 16.0, top: 8.0),
              child: content,
            ),
          ),
        ],
      ),
    );
  }
} 